package com.driver.manage.ocr;

import org.apache.log4j.Logger;
import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.videoio.VideoCapture;

public class DetectFace {
    static int i=0;
    static CascadeClassifier faceDetector;
    private static Logger logger = Logger.getLogger(DetectFace.class);
    private final static String faceOutPutDir = "D:\\Documents\\Pictures";
    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        faceDetector = new CascadeClassifier("D:\\SoftWare\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml");
    }

    public static String detectFace() {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        // Mat src =
        // Imgcodecs.imread("/Users/chrishu123126.com/opt/img/detect-face-4.jpg");
//        Mat src = Imgcodecs.imread("D:\\Documents\\1687920535134.jpg");
//        if (src.empty()) {
//            System.out.println("图片路径不正确");
//            return;
//        }
        getVideoFromCamera();
//        Mat dst = dobj(src);
//        ImageViewer imageViewer = new ImageViewer(dst, "识脸");
//        imageViewer.imshow();
        return null;
    }
    /**
     * TODO  通过摄像头截取人脸
     *
     * @date 2023/6/28 18:54
     * @author 86131
     * @param
     * @return {@link boolean}
     */
    public static final boolean getFace(){

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        return  getVideoFromCamera();
    }

    private static Mat dobj(Mat src) {
        Mat dst = src.clone();

        MatOfRect objDetections = new MatOfRect();

        faceDetector.detectMultiScale(dst, objDetections);

        if (objDetections.toArray().length <= 0) {
            return src;
        }
        System.out.println("333333");

        for (Rect rect : objDetections.toArray()) {
            Imgproc.rectangle(dst, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.width),
                    new Scalar(0, 255, 0), 1); // new Scalar(0, 255, 0), 1)绿 //new Scalar(0, 0, 255), 1)红 //new
            // Scalar(255, 0, 0), 1)蓝
            outputFace(faceOutPutDir, src.submat(rect));
        }
        return dst;
    }

    private static void outputFace(String outputDir, Mat face) {
        long millSecs = System.currentTimeMillis();
        int temp = (int) (Math.random() * 10000);
        StringBuffer outputImgName = new StringBuffer();
        outputImgName.append(outputDir).append("/").append(millSecs).append(temp).append(".jpg");
        System.out.println("aaaaaaa");
        if (face != null) {
            Imgcodecs.imwrite(outputImgName.toString(), face);
            logger.info(">>>>>>write image into->" + outputDir);
        }
    }

    /**
     * OpenCV-4.1.1 从摄像头实时读取
     * @return: void
     * @date: 2019年8月19日 17:20:13
     */
    public static boolean getVideoFromCamera() {
        //1 如果要从摄像头获取视频 则要在 VideoCapture 的构造方法写 0
        VideoCapture capture=new VideoCapture(0);
        Mat video=new Mat();
        int index=0;
        if (capture.isOpened()) {
            while(i<3) {// 匹配成功3次退出
                capture.read(video);
                System.out.println("人脸识别");
                HighGui.imshow("实时人脸识别", getFace(video));
                index=HighGui.waitKey(100);
                if (index==27) {
                    capture.release();
                    break;
                }
            }
        }else{
            System.out.println("摄像头未开启");
        }
        try {
            capture.release();
            Thread.sleep(1000);
            System.exit(0);
            return  true;
        } catch (InterruptedException e) {
            System.out.println("报错了1");
            e.printStackTrace();
            return  false;
        }

    }


    /**
     * OpenCV-4.1.1 人脸识别
     * @date: 2019年8月19日 17:19:36
     * @param image 待处理Mat图片(视频中的某一帧)
     * @return 处理后的图片

     */
    public static Mat getFace(Mat image) {
        // 1 读取OpenCV自带的人脸识别特征XML文件(faceDetector)
//        CascadeClassifier facebook=new CascadeClassifier("D:\\Sofeware\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml");
        // 2  特征匹配类
        MatOfRect face = new MatOfRect();
        // 3 特征匹配
        faceDetector.detectMultiScale(image, face);
        Rect[] rects=face.toArray();
        if (rects.length>1){

        }
        System.out.println("匹配到 "+rects.length+" 个人脸");
        if(rects != null && rects.length >= 1) {

            // 4 为每张识别到的人脸画一个圈
            for (int i = 0; i < rects.length; i++) {
                Imgproc.rectangle(image, new Point(rects[i].x, rects[i].y), new Point(rects[i].x + rects[i].width, rects[i].y + rects[i].height), new Scalar(0, 255, 0));
                Imgproc.putText(image, "Human", new Point(rects[i].x, rects[i].y), Imgproc.FONT_HERSHEY_SCRIPT_SIMPLEX, 1.0, new Scalar(0, 255, 0), 1, Imgproc.LINE_AA, false);
                Mat dst=image.clone();
//                Imgproc.resize(image, image, new Size(300,300));

            }

            i++;
            if(i==3) {// 获取匹配成功第3次的照片
//                Imgcodecs.imwrite("D:\\Documents\\Pictures\\" + "face.png", image);
                dobj(image);
            }
        }
        return image;
    }
}